package com.wn.netty.sample;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @FileName: MyClientChannelHandler
 * @Description: TODO
 * @Author: MaWenHao
 * @Created: 2020/7/28 - 17:52
 * @Version: V1.0
 * @Company: 东方微银科技（北京）有限公司
 */
public class MyClientChannelHandler extends ChannelInboundHandlerAdapter {

    /**
     * 通道准备就绪后,发送消息
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello 服务器...", CharsetUtil.UTF_8));
        System.out.println("发送消息完成, ChannelHandlerContext: " + ctx);
    }

    /**
     * 读取服务器应答
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("服务器应答的消息: " + buf.toString(CharsetUtil.UTF_8));
        System.out.println("服务器地址: " + ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
